import 'dart:developer';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flick_video_player/flick_video_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/comment_view_logic.dart';
import 'package:ball_lion/module/home/news_detail_logic.dart';
import 'package:ball_lion/entity/home/news_item_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/server/api/home_api.dart';
import 'package:ball_lion/utils/local_read_history.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/home/comments/comment_input_widget.dart';
import 'package:ball_lion/module/home/comments/news_comments_view.dart';
import 'package:ball_lion/module/home/news_cell.dart';
import 'package:ball_lion/module/home/video/video_player.dart' as player;
import 'package:video_player/video_player.dart';

import 'package:ball_lion/widgets/base/wqs_text.dart';

class VideoNewsPage extends StatefulWidget {
  const VideoNewsPage({super.key});

  @override
  State<VideoNewsPage> createState() => _VideoNewsPageState();
}

class _VideoNewsPageState extends State<VideoNewsPage>
    with TickerProviderStateMixin {
  int id = Get.arguments;
  final logic = Get.put(NewsDetailLogic(), tag: '${Get.arguments}');
  final commentLogic = Get.put(CommentViewLogic(), tag: '${Get.arguments}');

  int? classId = () {
    log("Get parameters = ${Get.parameters}");
    return Get.parameters['classId'] == null
        ? null
        : int.parse(Get.parameters['classId']!);
  }.call();
  NewsItemEntity? data;

  List<NewsItemEntity> get recommendList => data?.list ?? [];

  final tabs = ['简介', '评论'];
  late final tabController = TabController(length: tabs.length, vsync: this);
  FlickManager? flickManager;
  VideoPlayerController? playerController;

  // fetchRecommend() async {
  //   Api.getNewsRecommendList(id, classId).then((value) {
  //     log("$value id = $id classId = $classId");
  //     final list = value.data['d'].map<NewsItemEntity>((e) => NewsItemEntity.fromJson(e)).toList();
  //     recommendList = list;
  //     update();
  //   }).catchError((err) {
  //     log("$err");
  //   });
  // }

  getData() async {
    NewsItemEntity? result = await HomeApi.getNews2(id, classId: classId);
    playerController =
        VideoPlayerController.networkUrl(Uri.parse(result.video ?? ''));
    flickManager = FlickManager(
      videoPlayerController: playerController!,
      getPlayerControlsTimeout: (
          {errorInVideo, isPlaying, isVideoEnded, isVideoInitialized}) {
        return const Duration(seconds: 5);
      },
    );
    data = result;
    update();
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
    getData();
    // commentController.fetchCommentds();
    // fetchRecommend();
    LocalReadHistory.readNews("$id");
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (flickManager!.flickControlManager!.isFullscreen) {
          flickManager!.flickControlManager!.exitFullscreen();
          return false;
        }
        return true;
      },
      child: Scaffold(
        body: data == null
            ? Container()
            : GetBuilder<NewsDetailLogic>(
                tag: '${Get.arguments}',
                builder: (_) {
                  return Column(
                    // crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        color: Colours.black,
                        child: SafeArea(
                            bottom: false,
                            child: player.VideoPlayer(data?.video ?? "",
                                flickManager!, playerController!)),
                      ),
                      Container(
                          color: Colors.white,
                          alignment: Alignment.centerLeft,
                          child: Styles.tabbar(
                                  scrollable: true,
                                  controller: tabController,
                                  tabs: tabs
                                      .map((e) => QsText(e)
                                          .marginSymmetric(horizontal: 8))
                                      .toList())
                              .sized(height: 44)
                              .marginOnly(left: 8)),
                      Expanded(
                        child: ExtendedTabBarView(
                            controller: tabController,
                            children: [
                              infoView(),
                              // Center(child: QsText("1"),),
                              commentView()
                            ]),
                      )
                    ],
                  );
                },
              ),
      ),
    ).tap(
      () {
        FocusScope.of(context).unfocus();
      },
    );
  }

  commentView() {
    return Container(
      color: Colors.white,
      child: Column(
        children: [
          Expanded(
              child: EasyRefresh(
            onLoad: !commentLogic.hasMoreComment
                ? null
                : () async {
                    await commentLogic.fetchComments();
                  },
            child: SingleChildScrollView(
                child: NewsCommentsView(
              id,
              paddingTop: MediaQuery.of(context).padding.top,
              showTop: false,
            )),
          )),
          SafeArea(
              top: false,
              child: CommentInputWidget(
                numberBtn: false,
                news: data,
                cid: classId,
                textId: "$id",
                newsId: id,
              ))
        ],
      ),
    );
  }

  infoView() {
    return Container(
      color: Colours.greyF7,
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          // Container(color: Colors.blue,height: 80,)
          titleWidget(),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            child: Column(
              children: [
                ...List.generate(
                    recommendList.length,
                    (index) => NewsItemCell(recommendList[index],
                        inHome: false,
                        imgStyle: 2,
                        classId: classId,
                        bottomDivider: index < recommendList.length - 1))
              ],
            ),
          ),
        ],
      ),
    );
  }

  titleWidget() {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 14, 16, 20),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          QsText(
            data!.title!,
            maxLines: 2,
            fontSize: 20,
            color: Colours.text,
            fontWeight: FontWeight.w500,
          ),
          const SizedBox(height: 12),
          Row(
            children: [
              Stack(
                children: [
                  ClipOval(
                    child: CachedNetworkImage(
                      imageUrl: data?.logo ?? '',
                      width: 32,
                      height: 32,
                    ),
                  ),
                  Positioned(
                      right: 0,
                      bottom: 0,
                      child: Image.asset(Utils.getImgPath('v.png'), width: 12))
                ],
              ),
              const SizedBox(width: 10),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  QsText(
                    data?.publisherName ?? '',
                    fontSize: 16,
                    fontWeight: FontWeight.w500,
                  ),
                  QsText(
                    data?.info ?? '',
                    fontSize: 11,
                    color: Colours.grey99,
                  ),
                ],
              )
            ],
          )
        ]),
      ),
    );
  }
}
